<?php
/*------------------------------------------------------------------------
 # Sot Article Class  - Version 1.0
 # Copyright (C) 2010-2011 Sky Of Tech. All Rights Reserved.
 # @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 # Author: Sky Of Tech
 # Websites: http://skyoftech.com
 -------------------------------------------------------------------------*/
 
jimport( 'joomla.filesystem.file' );
require_once JPATH_SITE.'/components/com_content/helpers/route.php';

jimport('joomla.application.component.model');

JModel::addIncludePath(JPATH_SITE.'/components/com_content/models', 'ContentModel');

require_once (JPATH_SITE .DS.'modules'.DS.$module->module.DS.'libs'.DS.'SimpleImage'.DS.'SimpleImage.php');

if (! class_exists("SotArticles") ) {
class SotArticles {
	var $sections_cates = array();
	var $article_ids = array();	
	var $is_frontpage = 0;	// 0 - without frontpage, 1 - only frontpage - 2 both
	var $type = 0;
	var $limit = 5;	
	var $sort_order_field = 'created';
	var $type_order = 'ASC';	
	var $thumb_width = '40';
	var $thumb_height = '40';
	var $web_url = '';	
	var $cropresizeimage = 0;
	var $max_title = 0;
	var $max_description = 0;
	var $max_short_desc = 0;
	var $resize_folder = '';
	var $crop_folder = '';
	var $url_to_resize = '';
	var $url_to_crop = '';
	
	function Article() {
		
	}
		
	function getList($params) {
			$db = JFactory::getDbo();
 
			// Get an instance of the generic articles model
			$model = JModel::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
	 
			// Set application parameters in model
			$app = JFactory::getApplication();
			$appParams = $app->getParams();
			$model->setState('params', $appParams);
	
			// Set the filters based on the module params
			$model->setState('list.start', 0);
			$model->setState('list.limit', (int) $params->get('count', 5));
			$model->setState('filter.published', 1);
	
			// Access filter
			$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
			$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
			$model->setState('filter.access', $access);
	
			// Category filter
			if($params->get('source', 1)==1)
			{
				$model->setState('filter.category_id', $params->get('catid', array()));
			} 
			else if($params->get('source', 1)==2)
			{
				$model->setState('filter.article_id', explode(",",$params->get('item_ids', '')));
			}
	
			// User filter
			$userId = JFactory::getUser()->get('id');
			switch ($params->get('user_id'))
			{
				case 'by_me':
					$model->setState('filter.author_id', (int) $userId);
					break;
				case 'not_me':
					$model->setState('filter.author_id', $userId);
					$model->setState('filter.author_id.include', false);
					break;
	
				case '0':
					break;
	
				default:
					$model->setState('filter.author_id', (int) $params->get('user_id'));
					break;
			}
	
			// Filter by language
			$model->setState('filter.language',$app->getLanguageFilter());
	
			//  Featured switch
			switch ($params->get('show_featured'))
			{
				case '1':
					$model->setState('filter.featured', 'only');
					break;
				case '0':
					$model->setState('filter.featured', 'hide');
					break;
				default:
					$model->setState('filter.featured', 'show');
					break;
			}
	
			// Set ordering
			$order_map = array(
				'm_dsc' => 'a.modified DESC, a.created',
				'mc_dsc' => 'CASE WHEN (a.modified = '.$db->quote($db->getNullDate()).') THEN a.created ELSE a.modified END',
				'c_dsc' => 'a.created',
				'p_dsc' => 'a.publish_up',
			);
			$ordering = JArrayHelper::getValue($order_map, $params->get('ordering'), 'a.publish_up');
			$dir = 'DESC';
	
			$model->setState('list.ordering', $ordering);
			$model->setState('list.direction', $dir);
	
			$items = $model->getItems();
			//var_dump($items);die;
			foreach ($items as &$item) {
				$item->slug = $item->id.':'.$item->alias;
				$item->catslug = $item->catid.':'.$item->category_alias;
	
				if ($access || in_array($item->access, $authorised)) {
					// We know that user has the privilege to view the article
					$item->link = JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catslug));
				} else {
					$item->link = JRoute::_('index.php?option=com_users&view=login');
				}
			}
			
			$rows = $items;
			
			$items = array();
			for($i = 0; $i < count ( $rows ); $i ++) {
				$rows [$i]->text = $rows [$i]->introtext;
				
				$rows [$i]->introtext = $rows [$i]->text;
				$items[$i]['id'] = $rows [$i]->id;
				$items[$i]['img'] = $this->getImage($rows [$i]->text);
				$items[$i]['title'] = $rows[$i]->title;
				if($this->keep_html_tag)
				{
					$items[$i]['content'] = $this->removeImage($rows [$i]->text);
				}
				else
				{
					$items[$i]['content'] = strip_tags($this->removeImage($rows [$i]->text));
				}
				
				$items[$i]['hits'] 				= $rows [$i]->hits;
				$items[$i]['created'] 			= $rows [$i]->created;
				$items[$i]['created_by_alias'] 	= $rows [$i]->created_by_alias;
				$items[$i]['author'] 			= $rows [$i]->author;	
				$items[$i]['link'] = $rows [$i]->link;
			}
			//var_dump($items);die;
			if(count($items)>0){
				$items = $this->update($items);
			} else {
				return array();
			}	
			
			return $items;
		}		
	
	
	function getImage($str){
			
    		$regex = "/\<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>/";
    		$matches = array();
			preg_match ( $regex, $str , $matches );    
			$images = (count($matches)) ? $matches : array ();
			$image = count($images) > 1 ? $images[1] : '';
						
			return $image;
	}
	
	function getItemid($sectionid) {
		$contentConfig = &JComponentHelper::getParams ( 'com_content' );
		$noauth = ! $contentConfig->get ( 'shownoauth' );
		$user = & JFactory::getUser ();
		$aid = $user->get ( 'aid', 0 );
		$db = & JFactory::getDBO ();
		$query = "SELECT id FROM #__menu WHERE `link` like '%option=com_content%view=section%id=$sectionid%'" . ' AND published = 1' . ($noauth ? ' AND access <= ' . ( int ) $aid : '');
		
		$db->setQuery ( $query );
		return $db->loadResult ();
	}
	
	function removeImage($str) {
		$regex1 = "/\<img[^\>]*>/";
		$str = preg_replace ( $regex1, '', $str );
		$regex1 = "/<div class=\"mosimage\".*<\/div>/";
		$str = preg_replace ( $regex1, '', $str );
		$str = trim ( $str );
		
		return $str;
	}
		
	
	function update($items) {
		$tmp = array();
		
		foreach ($items as $key => $item) {
			if (!isset($item['sub_title'])) {
				$item['sub_title'] = $this->truncate($item['title'], $this->max_title, '...', true, true);
			}
			
			if (!isset($item['sub_content'])) {
				$content = $this->truncate($item['content'], $this->max_description, '...', true, true);
				$item['sub_content'] = $content;
			}
			
			if (!isset($item['sub_short_content'])) {
				$content = $this->substrwords($item['content'], $this->max_short_desc, '...');
				$item['sub_short_content'] = $content;
			}
			
			if (!isset($item['thumb']) && $item['img'] != '') {
				$item['thumb'] = $this->processImage($item['img'], $this->thumb_width, $this->thumb_height);
			} else {
				$item['thumb'] = '';
			}		
			
			if (!isset($item['small_thumb']) && $item['img'] != '') {
				$item['small_thumb'] = $this->processImage($item['img'], $this->small_thumb_width, $this->small_thumb_height);
			} else {
				$item['small_thumb'] = '';
			}
			
			$item['created'] 			= $item['created'];
			$item['created_by_alias'] 	= $item['created_by_alias'];
			$item['author'] 			= $item['author'];
			
			if ($item['thumb'] != '') {			
				$tmp[] = $item;
			}
		}
		
		return $tmp;				
	}
	
	function processImage($img, $width, $height) {
				
		if ($this->cropresizeimage == 0) {
			return $this->resizeImage($img, $width, $height);
		} else {
			return $this->cropImage($img, $width, $height);
		}
	}
		
	function resizeImage($imagePath, $width, $height) {
		global $module;
				
		$folderPath = $this->resize_folder;
		
		$parent_path = str_replace("/images/resize","",$folderPath);
		$parent_path = str_replace("\\images\\resize","",$parent_path);
		
		if(!JFolder::exists($parent_path)){
			if(mkdir($parent_path, 0777)){
			
			} else {
				echo "Error: Can't create folder for resize image!"; exit();
			}
		}
		
		$parent_path = str_replace("/resize","",$folderPath);
		$parent_path = str_replace("\\resize","",$parent_path);
		
		if(!JFolder::exists($parent_path)){
			//if(JFolder::create($folderPath)){echo "ok";} else {echo "not ok";}	 
			if(mkdir($parent_path, 0777)){
				if(mkdir($folderPath, 0777)){
				
				} else {
					echo "Error: Can't create folder for resize image!"; 
				}	
			} else {
				echo "Error: Can't create folder for resize image!"; 
			}	 
		} else
		{
		 if(!JFolder::exists($folderPath)){
			if(mkdir($folderPath, 0777)){
				
			} else {
				echo "Error: Can't create folder for resize image!"; 
			}	
		 
		 }
		}
		  
		 $nameImg = str_replace('/','',strrchr($imagePath,"/"));		
		 $ext = substr($nameImg, strrpos($nameImg, '.'));
		 $file_name = substr($nameImg, 0,  strrpos($nameImg, '.'));
		 $nameImg = $file_name . "_" . $width . "_" . $height .  $ext;
		 		 
		 if(!JFile::exists($folderPath.DS.$nameImg)){
			 $image = new SimpleImage();
	  		 $image->load($imagePath);
	  		 $image->resize($width,$height);
	   		 $image->save($folderPath.DS.$nameImg);
		 }else{
		 		 list($info_width, $info_height) = @getimagesize($folderPath.DS.$nameImg);
		 		 if($width!=$info_width||$height!=$info_height){
		 		 	 $image = new SimpleImage();
	  				 $image->load($imagePath);
	  				 $image->resize($width,$height);
	   				 $image->save($folderPath.DS.$nameImg);
		 		 }
		 }
   		 return $this->url_to_resize . $nameImg;
	}
	
	function cropImage($imagePath, $width, $height) {
		global $module;
		
		$folderPath = $this->crop_folder;
		
		$parent_path = str_replace("/images/crop","",$folderPath);
		$parent_path = str_replace("\\images\\\crop","",$parent_path);
		
		if(!JFolder::exists($parent_path)){
			if(mkdir($parent_path, 0777)){
			
			} else {
				echo "Error: Can't create folder for resize image!"; exit();
			}
		}
		
		$parent_path = str_replace("/crop","",$folderPath);
		$parent_path = str_replace("\\crop","",$parent_path);
			 
		 if(!JFolder::exists($parent_path)){
				//if(JFolder::create($folderPath)){echo "ok";} else {echo "not ok";}	 
				if(mkdir($parent_path, 0777)){
					if(mkdir($folderPath, 0777)){
					
					} else {
						echo "Error: Can't create folder for crop image!"; 
					}	
				} else {
					echo "Error: Can't create folder for crop image!"; 
				}	 
		 } else
		 {
			 if(!JFolder::exists($folderPath)){
				if(mkdir($folderPath, 0777)){
					
				} else {
					echo "Error: Can't create folder for crop image!"; 
				}	
			 
			 }
		 }
		 
		$nameImg = str_replace('/','',strrchr($imagePath,"/")); 
		$ext = substr($nameImg, strrpos($nameImg, '.'));
		$file_name = substr($nameImg, 0,  strrpos($nameImg, '.'));
	 	$nameImg = $file_name . "_" . $width . "_" . $height .  $ext;	 
		 
		 if(!JFile::exists($folderPath.DS.$nameImg)){
			 $image = new SimpleImage();
	  		 $image->load($imagePath);
	  		 $image->crop($width,$height);
	   		 $image->save($folderPath.DS.$nameImg);
		 }else{
		 		 list($info_width, $info_height) = @getimagesize($folderPath.DS.$nameImg);
		 		 if($width!=$info_width||$height!=$info_height){
		 		 	 $image = new SimpleImage();
	  				 $image->load($imagePath);
	  				 $image->crop($width,$height);
	   				 $image->save($folderPath.DS.$nameImg);
		 		 }
		 }
		 
   		 return $this->url_to_crop . $nameImg;
	}
	
	/**
	 * Truncates text.
	 *
	 * Cuts a string to the length of $length and replaces the last characters
	 * with the ending if the text is longer than length.
	 *
	 * @param string  $text String to truncate.
	 * @param integer $length Length of returned string, including ellipsis.
	 * @param string  $ending Ending to be appended to the trimmed string.
	 * @param boolean $exact If false, $text will not be cut mid-word
	 * @param boolean $considerHtml If true, HTML tags would be handled correctly
	 * @return string Trimmed string.
	 */
	function truncate($text, $length = 100, $ending = '...', $exact = true, $considerHtml = false) {
		if ($considerHtml) {
			// if the plain text is shorter than the maximum length, return the whole text
			if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
				return $text;
			}
			// splits all html-tags to scanable lines
			preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
			$total_length = strlen($ending);
			$open_tags = array();
			$truncate = '';
			foreach ($lines as $line_matchings) {
				// if there is any html-tag in this line, handle it and add it (uncounted) to the output
				if (!empty($line_matchings[1])) {
					// if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
					if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
						// do nothing
					// if tag is a closing tag (f.e. </b>)
					} else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
						// delete tag from $open_tags list
						$pos = array_search($tag_matchings[1], $open_tags);
						if ($pos !== false) {
							unset($open_tags[$pos]);
						}
					// if tag is an opening tag (f.e. <b>)
					} else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
						// add tag to the beginning of $open_tags list
						array_unshift($open_tags, strtolower($tag_matchings[1]));
					}
					// add html-tag to $truncate'd text
					$truncate .= $line_matchings[1];
				}
				// calculate the length of the plain text part of the line; handle entities as one character
				$content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
				if ($total_length+$content_length> $length) {
					// the number of characters which are left
					$left = $length - $total_length;
					$entities_length = 0;
					// search for html entities
					if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
						// calculate the real length of all entities in the legal range
						foreach ($entities[0] as $entity) {
							if ($entity[1]+1-$entities_length <= $left) {
								$left--;
								$entities_length += strlen($entity[0]);
							} else {
								// no more characters left
								break;
							}
						}
					}
					$truncate .= substr($line_matchings[2], 0, $left+$entities_length);
					// maximum lenght is reached, so get off the loop
					break;
				} else {
					$truncate .= $line_matchings[2];
					$total_length += $content_length;
				}
				// if the maximum length is reached, get off the loop
				if($total_length>= $length) {
					break;
				}
			}
		} else {
			if (strlen($text) <= $length) {
				return $text;
			} else {
				$truncate = substr($text, 0, $length - strlen($ending));
			}
		}
		// if the words shouldn't be cut in the middle...
		if (!$exact) {
			// ...search the last occurance of a space...
			$spacepos = strrpos($truncate, ' ');
			if (isset($spacepos)) {
				// ...and cut the text in this position
				$truncate = substr($truncate, 0, $spacepos);
			}
		}
		// add the defined ending to the text
		$truncate .= $ending;
		if($considerHtml) {
			// close all unclosed html-tags
			foreach ($open_tags as $tag) {
				$truncate .= '</' . $tag . '>';
			}
		}
		return $truncate;
	}

	function substrwords($text,$maxchar,$end='...'){
		$text = strip_tags($text);
		if(strlen($text)>$maxchar){
			$words=explode(" ",$text);
			$output = '';
			$i=0;
			while(1){
			$length = (strlen($output)+strlen($words[$i]));
				if($length>$maxchar){
					break;
				}else{
					$output = $output." ".$words[$i];
					++$i;
				};
			};
		}else{
			$output = $text;
		}
		return $output.$end;
	}
	
}
}


?>
